#include <iostream>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Resage(const std::string &str)
{
    std::cerr << "请输入：" << str.c_str() << "主机名 端口号 " << std::endl;
    exit(0);
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Resage(argv[0]);
        exit(0);
    }
    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    int _fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (_fd < 0)
    {
        std::cout << "创建socket失败" << std::endl;
        exit(1);
    }

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr =inet_addr(serverip.c_str());
    while(true)
    {
        std::cout<<"请输入要翻译的单词：";
        std::string line;
        std::getline(std::cin,line);
        sendto(_fd,line.c_str(),line.size(),0,(struct sockaddr*)&server,sizeof(server));

        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        int n=recvfrom(_fd,buffer,sizeof(buffer),0,(struct sockaddr*)&temp,&len);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<buffer<<std::endl;
        }
    }
    return 0;
}